<template>
  <div class="exam-create-container">
    <el-card class="box-card">
        <el-form 
            ref="formRef" 
            :rules="rules"
            :model="form">
            <el-row>
              <el-col :span="8">
                <el-form-item label="年级：" prop="level" required >
                  <el-select v-model="form.level" placeholder="请选择年级"  @change="changeLevel" style="width:100%">
                    <el-option v-for="item in options" :key="item.label" :value="item.value" :label="item.label"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <!-- 学科名称 -->
                <el-form-item label="学科" prop="subjectId">
                  <el-select v-model="form.subjectId" style="width:100%">
                      <el-option
                        placeholder="请选择学科"
                        v-for="item in subjectList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id+''">
                      </el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                  <!-- 学科名称 -->
                  <el-form-item label="试卷类型" prop="paperType">
                    <el-select v-model="form.paperType" style="width:100%" @change="changePaperType">
                        <el-option  v-for=" item in paperTypeOptions" :key="item.value" :value="item.value+''" :label="item.label"></el-option>
                      </el-select>
                  </el-form-item>
              </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="试卷名称"  prop="name" required>
                <el-input v-model="form.name" style="width:100%"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="建议时长" prop="suggestTime" required>
                <!-- <el-input v-model="form.suggestTime" placeholder="分钟"/> -->
                 <el-input-number v-model="form.suggestTime" placeholder="分钟" style="width:100%;" controls-position="right" @change="handleChange"></el-input-number>
              </el-form-item>
            </el-col>
             <el-col :span="8">
                <el-form-item label="时间限制" required v-show="timeLimit">
                  <el-date-picker v-model="form.limitDateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
                          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width:100%;">
                  </el-date-picker>
                </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <span v-if="form.titleItems.length!==0" class="topic-list">题目列表</span>
              <el-form-item :key="index" :label="'标题'+(index+1)+'：'" required v-for="(titleItem,index) in form.titleItems">
                <el-input v-model="titleItem.name" style="width: 80%"/>
                <el-button type="text" class="link-left" style="margin-left: 20px;color:#1980FF;" size="mini" @click="addQuestion(titleItem)">
                  添加题目
                </el-button>
                <el-button type="text" class="link-left" style="color:#F56C6C;" size="mini" @click="form.titleItems.splice(index,1)">删除</el-button>
                <el-card class="exampaper-item-box" v-if="titleItem.questionItems.length!==0">
                  <el-form-item :key="questionIndex" :label="'题目'+(questionIndex+1)+'：'"
                                v-for="(questionItem,questionIndex) in titleItem.questionItems" style="margin-bottom: 15px">
                    <el-row>
                      <el-col :span="23">
                        <QuestionShow :qType="questionItem.questionType" :question="questionItem"/>
                      </el-col>
                      <el-col :span="1">
                        <el-button type="text" size="mini" style="color:#F56C6C;" @click="titleItem.questionItems.splice(questionIndex,1)">删除
                        </el-button>
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-card>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item>
                <div class="btns">
                  <template v-if="form.id === null">
                    <el-button class="btn" type="success" @click="submitForm">保存</el-button>
                  </template>
                  <template v-else>
                    <el-button class="btn" type="success" @click="updateForm">更新</el-button>
                  </template>
                  <el-button class="btn" type="primary" @click="addTitle">添加标题</el-button>
                  <el-button class="btn" type="danger" @click="resetForm">重置</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
    </el-card>
    <el-dialog title="题目信息" 
        :modal-append-to-body="false"
        :visible.sync="questionPage.showDialog" 
        width="70%">
       <el-form style="margin-bottom:20px;width:100%;" class="queryForm" :model="questionPage.queryParam" ref="queryForm">
          <el-row>
            <el-col :span="8" style="margin-right:10px;">
              <el-form-item label="ID">
                <el-input v-model="questionPage.queryParam.id" @clear="search" clearable style="width:100%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="题型">
                <el-select placeholder="请选择题型" @clear="search" v-model="questionPage.queryParam.questionType" style="width:100%" clearable>
                  <el-option label="单选题" value="1"></el-option>
                  <el-option label="多选题" value="2"></el-option>
                  <el-option label="判断题" value="3"></el-option>
                  <el-option label="填空题" value="4"></el-option>
                  <el-option label="简答题" value="5"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item>
                <el-button type="primary" @click="queryForm">查询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
      </el-form>
      <el-table :data="questionPage.tableData"
                @selection-change="handleSelectionChange" border fit highlight-current-row style="width: 100%">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="id" label="Id" width="60px"/>
        <el-table-column label="题型" width="120px">
              <template slot-scope="scope">
                <span v-if="scope.row.questionType=== 1">单选题</span>
                <span v-if="scope.row.questionType=== 2">多选题</span>
                <span v-if="scope.row.questionType=== 3">判断题</span>
                <span v-if="scope.row.questionType=== 4">填空题</span>
                <span v-if="scope.row.questionType=== 5">简答题</span>
              </template>
        </el-table-column>
        <el-table-column prop="shortTitle" label="题干"/>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
            style="margin-top:20px;"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="pagination"
            :current-page="questionPage.queryParam.pageIndex"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="questionPage.queryParam.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="questionPage.total">
      </el-pagination>
       <span slot="footer" class="dialog-footer">
          <el-button class="saveBtn" type="primary" @click="confirmQuestionSelect">保存</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import QuestionShow from '../question/component/question';

export default {
  components: {  QuestionShow },
  data(){
    return {
      form: {
        id: null,
        level: null,
        subjectId: null,
        paperType: 2+'',
        limitDateTime: [],
        name: '',
        suggestTime: null,
        titleItems: []
      },
      //校验规则
      rules: {
        level: [
          { required: true, message: '请选择年级', trigger: 'change' }
        ],
        subjectId: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        paperType: [
          { required: true, message: '请选择试卷类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入试卷名称', trigger: 'blur' }
        ],
        suggestTime: [
          { required: true, message: '请输入建议时长', trigger: 'blur' }
        ]
      },
      //年级选择
      options: [{
        value: '1',
        label: '一年级'
      }, {
        value: '2',
        label: '二年级'
      }, {
        value: '3',
        label: '三年级'
      }, {
        value: '4',
        label: '四年级'
      }, {
        value: '5',
        label: '五年级'
      }, {
        value: '6',
        label: '六年级'
      }, {
        value: '7',
        label: '初一'
      }, {
        value: '8',
        label: '初二'
      }, {
        value: '9',
        label: '初三'
      }, {
        value: '10',
        label: '高一'
      }, {
        value: '11',
        label: '高二'
      }, {
        value: '12',
        label: '高三'
      }],
      subjectList:[],// 学科列表
      paperTypeOptions:[{
        value:1,
        label: "固定试卷"
      },{
        value:2,
        label: "时段试卷"
      },{
        value:3,
        label: "任务试卷"
      },{
        value:4,
        label: "班级试卷"
      },{
        value:5,
        label: "智能试卷"
      }],
      timeLimit:true,//控制时间限制的显示与隐藏
      //添加题目分页显示
      questionPage: {
        multipleSelection: [],
        showDialog: false,
        queryParam: {
          id: null,
          questionType: null,
          subjectId: 1,
          pageIndex: 1,
          pageSize: 5
        },
        listLoading: true,
        tableData: [],
        total: 0
      },
      currentTitleItem: null
    }
  },
  created(){
    //编辑操作
    console.log(this.examPaperId);
    if( this.examPaperId != null && this.examPaperId !=''){
      this.getExamPaperById(this.examPaperId);
    }
  },
  computed:{
    //试卷id
    examPaperId(){
      return this.$store.state.examPaperId;
    }
  },
  methods:{
    //根据id查询试卷
    getExamPaperById(id){
      this.getRequest("/api/admin/exam/paper/select/"+id).then(re => {
        if( re && re.code ==200){
           this.changeLevel( re.obj.level );
           this.changePaperType( re.obj.paperType );
            re.obj.level = re.obj.level + '';
            re.obj.subjectId = re.obj.subjectId +'';
            re.obj.paperType = re.obj.paperType + '';
            
            this.form = re.obj;
        }
      })
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
        //console.log(newSize);
        this.questionPage.queryParam.pageSize = newSize;
        this.search();
    },
    //监听页码值改变的事件
    handleCurrentChange(newPage) {
        //console.log(newPage);
        this.questionPage.queryParam.pageIndex = newPage
        this.search();
    },
    //切换班级时
    changeLevel(value){
      this.getRequest("/api/admin/subject/listBylevel",{
        level: value
      }).then( resp => {
        if(resp && resp.code == 200){
          this.subjectList = resp.obj;
        }
      })
    },
    //切换试卷类型
    changePaperType(value){
        
        if(value == 2 || value == "2"){
          this.timeLimit = true;
        }else{
          this.timeLimit = false;
        }
        console.log(this.timeLimit);
    },
    //计数器回调
    handleChange(value){
      this.form.suggestTime = value;
    },
    //添加题目
    addQuestion (titleItem) {
      this.currentTitleItem = titleItem
      this.questionPage.showDialog = true
      this.search()
    },
    search(){
      this.questionPage.queryParam.subjectId = this.form.subjectId
     
      this.getRequest("/api/admin/question/page",{
        pageIndex: this.questionPage.queryParam.pageIndex,
        pageSize: this.questionPage.queryParam.pageSize,
        questionType:this.questionPage.queryParam.questionType,
        id: this.questionPage.queryParam.id,
        subjectId : this.questionPage.queryParam.subjectId
      }).then(resp => {
        // const re = data.data
        this.questionPage.tableData = resp.data;
        this.questionPage.total = resp.total
      })
    },
    //添加标题
    addTitle(){
      this.form.titleItems.push({
        name: '',
        questionItems: []
      })
    },
    //查询题目列表
    queryForm(){
      //执行查询操作
      this.search();
    },
    //题目选中
    handleSelectionChange(val){
      this.questionPage.multipleSelection = val;
    },
    //保存题目
    confirmQuestionSelect(){
      let _this = this
      this.questionPage.multipleSelection.forEach(q => {
        this.getRequest("/api/admin/question/select/"+q.id).then(re => {
          if( re && re.code ==200){
               _this.currentTitleItem.questionItems.push(re.obj)
          }
        })
      })
      this.questionPage.showDialog = false
    },
    //创建题目
    submitForm(){
      this.$refs.formRef.validate( valid => {
        if(!valid){
          this.$message.error("请输入所有的必填项！");
          return false;
        }else{
          this.postRequest("/api/admin/exam/paper/edit",this.form).then( resp => {
            if(resp && resp.code == 200){
              //跳转试卷列表
              this.$router.replace("/admin/exam/list");
            }
          })
        } 
      })
    },
    //更新试卷
    updateForm(){
      this.$refs.formRef.validate( valid => {
        if(!valid){
          this.$message.error("请输入所有的必填项！");
          return false;
        }else{
          this.putRequest("/api/admin/exam/paper/edit",this.form).then(resp=>{
            if(resp && resp.code == 200){
              this.$store.commit("initExamPaperId","");
              this.$router.replace("/admin/exam/list");
            }
          })
        }
      })
    },
    //重置表单
    resetForm(){
      let lastId = this.form.id
      this.$refs.formRef.resetFields()
      this.form = {
        id: null,
        level: null,
        subjectId: null,
        paperType: 1,
        limitDateTime: [],
        name: '',
        suggestTime: null,
        titleItems: []
      }
      this.form.id = lastId
    }
  }
}
</script>

<style lang="scss" scoped>
.exam-create-container{
  font-family: "华文楷体";
  .box-card{
    border-radius: 10px;
    color:#1A1A1A;
    
    padding: 0 0 20px 0;.el-col{
      padding: 0 10px;
    }
    /deep/.el-button--mini:nth-child(1){
      margin-left: 20px;
      color:#66BB6A;
    }
    /deep/.el-button--mini:nth-child(2){
      margin-left: 20px;
      color:#F56C6C;
    }
    .topic-list{
      margin: 10px 0;
      font-size: 16px;
      font-weight: bold;
    }
    .btn{
      margin-top: 20px;
      font-size: 12px;
      padding: 10px 18px;
    }
    .link-left {
      margin-left: 5px;
    }
    .exampaper-item-box {
      margin: 10px 0 0 0;
      .q-title {
        margin: 0px 5px 0px 5px;
      }
      .q-item-content {
      }
    }
    .btns{
      display: flex;
      justify-content: flex-end;
      margin: 20px 0 10px 0 ;
      .btn{
        padding-left:  35px;
        padding-right:  35px;
        font-size: 14px;
        font-family: "华文楷体";
      }
    }
  }
 
  .saveBtn{
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #66BB6A;
      margin-bottom: 20px;
      font-family: "华文楷体";
  }
  .queryForm{
    /deep/.el-form-item {
      display: flex;
      flex-direction: row;
      width: 100%;
    }
  }
  .el-pagination{
    display: flex;
    justify-content: flex-end;
  }
  /deep/.el-form-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 10px !important;
  }
  /deep/.el-form-item__label{
    text-align: left;
  }
  /deep/.el-form-item__label-wrap {
    margin-left:  0 !important;
  }
}
</style>